#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import datetime
import re

DATE_TIME_FORMAT_STYLE_1 = '%y-%m-%d %X'
DATE_TIME_FORMAT_STYLE_2 = '%Y-%m-%d %X'

DATE_TIME_TYPE_FIELD = ['updated_at','deleted_at','created_at','locked_at','time','atime']


def encode_utf8(ucode):
    if isinstance(ucode, unicode):
        return ucode.encode('utf8')
    return ucode
    
    
def field_format(kw):
    field = {}
    for k,v in kw:
        if callable(v):
            pass
        elif isinstance(v, list):
            for i in v:
                if callable(i):
                    pass
        elif isinstance(v, datetime.datetime):
            v = time_format(v, DATE_TIME_FORMAT_STYLE_2)
            field[k] = v
        elif isinstance(v, unicode):
            field[k] = v.encode('utf8')
        else:
            field[k] = v

    return field


def time_format(time_str, datatime_format):
    return datetime.datetime.strftime(time_str, datatime_format)


def return_failure(error_str, internal_status):
    if internal_status == 100:
        code, description, status = "InvalidRequest", "The request is invalid", 400
    elif internal_status == 101:
        code, description, status = "ServiceUnavailable", "The service is not avaliable", 503
    elif internal_status == 102:
        code, description, status = "InvalidParams", "Something wrong with the params", 400
    elif internal_status == 103:
        code, description, status = "IllegalName", "The name is illegal", 400
    elif internal_status == 104:
        code, description, status = "DuplicateName", "The name is duplicate", 409
    elif internal_status == 105:
        code, description, status = "ResourceNotExist", "The resource is not exist", 404
    elif internal_status == 106:
        code, description, status = "ResourceUnavailable", "The resource is not avaliable", 409
    elif internal_status == 107:
        code, description, status = "ResourceNotEnough", "The resource is not enough", 416
    elif internal_status == 108:
        code, description, status = "ResourceInUse", "The resource is in use", 409
    elif internal_status == 109:
        code, description, status = "InvalidOperation", "The operation is not avaliable this resource", 403
    elif internal_status == 110:
        code, description, status = "MethodNotAllowed", "The specified method is not allowed against this resource", 405
    elif internal_status == 111:
        code, description, status = "InternalServerError", "Internal server error", 500
   
    rs_fail = {
               'error':{
                        "code": code,
                        "description": description,
                        "detail": str(error_str)
                        },
               "status": status
               }
    return rs_fail


def return_success(objs={}):
    rs_success = {'result':'success'}
    rs_success.update(objs)
    return rs_success
    
    
def verify_ip(ip_str):
    try:
        if len([x for x in ip_str.split('.') if int(x)<256]) == 4:return True
        else:return False
    except:
        return False
    
    
def verify_ip_and_port(ip_str):
    ip, sep, port = ip_str.partition(':')
    if verify_ip(ip):
        try:int(port)
        except:return False
        return True
    return False


def verify_d_c_input_name(str):
    "由3至16位中文、大小写英文字母、数字、中划线或下划线构成, unicode"
    if re.match(ur"[a-zA-Z0-9\u4e00-\u9fa5_-]{3,16}$", str):
        return True
    else:
        return False


def verify_description(str):
    "小于255个字符, unicode"
    if len(str) < 255:
        return True
    else:
        return False
    
    
def verify_host_name(str):
    "由3至32位中文、大小写英文字母、数字、中划线或下划线构成, unicode"
    if re.match(ur"[a-zA-Z0-9\u4e00-\u9fa5_-]{3,32}$", str):
        return True
    else:
        return False   
    
    
def verify_vpool_name(str):
    return verify_d_c_input_name(str)


def verify_server_name(str):
    return verify_host_name(str)
#
#
#def verify_server_name(str):
#    "由3至32位小写英文字母、数字、中划线,下划线,:或.构成, 首字母为英文，unicode"
#    if re.match(r"^[a-z]{1}[a-z0-9_:.-]{2,32}$", str):
#        return True
#    else:
#        return False  


def verify_volume_name(str):
    return verify_host_name(str)


def verify_num(num, min, max, equal=False):
    try:
        num = int(num)
    except:
        return False
    if equal:
        if (num >= min) and (num <= max):
            return True
    else:
        if (num > min) and (num < max):
            return True
    return False
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
